<template>
  <div>

    <!-- 
          头部导航：
            click-left：点击左边图标触发事件
            click-right：点击右边图标触发事件
       -->
    <van-nav-bar @click-left="$router.push({path:'/personal'})"
                 @click-right="$router.push({path:'/index'})"
                 title="个人信息编辑"
                 left-arrow>
      <template #right>
        <van-icon name="wap-home-o"
                  size="20"
                  color="#000" />
      </template>
    </van-nav-bar>
    <div class="content">
      <div class="head_img">
        <!-- <img src="../assets/img/3.png"
             alt=""> -->
        <img :src="userInfo.head_img|joinPath"
             alt="">
        <van-uploader :after-read="afterRead" />
      </div>
      <!-- 昵称 -->
      <van-cell title="昵称"
                is-link
                @click="nicknameDialog"
                :value="userInfo.nickname" />
      <!-- 编辑昵称弹出框 -->
      <van-dialog v-model="showNickname"
                  title="编辑昵称"
                  :before-close="nickNameClose"
                  @confirm="updateNickname"
                  show-cancel-button>
        <van-cell-group>
          <van-field v-model="nickname"
                     required
                     label="用户名"
                     placeholder="请输入用户名" />
        </van-cell-group>
      </van-dialog>

      <!-- 密码 -->
      <van-cell title="密码"
                is-link
                @click="showPassword=true"
                value="*******" />
      <van-dialog v-model="showPassword"
                  title="修改密码"
                  :before-close="passwordClose"
                  show-cancel-button>
        <van-cell-group>
          <van-field v-model="oldPassword"
                     required
                     label="原密码"
                     placeholder="请输入原密码" />
          <van-field v-model="newPassword"
                     required
                     label="新密码"
                     placeholder="请输入新密码" />
        </van-cell-group>
      </van-dialog>

      <!-- 性别 -->
      <van-cell title="性别"
                is-link
                @click="showGender=true"
                :value="userInfo.gender===0?'女':'男'" />
      <van-action-sheet v-model="showGender"
                        :actions="genders"
                        cancel-text="取消"
                        close-on-click-action
                        @select="updateGender">
      </van-action-sheet>
    </div>
  </div>
</template>

<script>
import { user, user_update } from '../api/user'
import { upload } from '../api/common'
export default {
  data() {
    return {
      userInfo: {},
      showNickname: false, //显示与隐藏编辑昵称弹窗
      nickname: '', //存放昵称
      showPassword: false, //显示与隐藏修改密码弹窗
      oldPassword: '', //存放原密码
      newPassword: '', //存放新密码
      showGender: false, //显示与隐藏编辑性别弹窗
      genders: [
        { gender: 0, name: '女' },
        { gender: 1, name: '男' },
      ],
    }
  },
  created() {
    //   添加加载效果
    this.$toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0, // 持续展示 toast
    })
    user(localStorage.getItem('userId')).then((res) => {
      this.userInfo = res.data.data
      this.$toast.clear()
    })
  },
  methods: {
    //   获取上传的图片对象
    afterRead(file) {
      //   添加加载效果
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0, // 持续展示 toast
      })
      //   注意：真正上传给后端的对象是file里面的file对象
      const fileObj = file.file
      //   console.log(fileObj);
      // 传文件必须使用 formData对象,
      const formData = new FormData()
      formData.append('file', fileObj)
      // 上传图片
      upload(formData).then((res) => {
        // console.log(1,res)
        // 调用修改头像的接口
        const url = res.data.data.url
        user_update(localStorage.getItem('userId'), { head_img: url }).then(
          (res) => {
            // console.log(2,res)
            // 更新头像
            this.userInfo.head_img = res.data.data.head_img
            this.$toast.success('头像更新成功')
          }
        )
      })
    },
    // 阻止昵称为空的时候，点击确认关闭弹窗
    // 调用 done()表示关闭弹窗
    // 调用 done(false)表示阻止关闭弹窗
    nickNameClose(action, done) {
      if (!this.nickname && action === 'confirm') {
        done(false)
      } else {
        done()
      }
    },
    // 点击显示修改昵称弹出层
    nicknameDialog() {
      this.showNickname = true
    },
    // 修改昵称
    updateNickname() {
      if (!this.nickname) {
        this.$toast.fail('昵称不能为空')
        return
      }
      this.$toast.loading({
        message: '修改中....',
        duration: 0,
        forbidClick: true,
      })
      user_update(localStorage.getItem('userId'), {
        nickname: this.nickname,
      }).then((res) => {
        if (res.data.message === '修改成功') {
          this.userInfo.nickname = this.nickname
          this.$toast.success(res.data.message)
        } else {
          this.$toast.fail(res.data.message)
        }
      })
    },
    // 修改密码
    passwordClose(actions, done) {
      // confirm  确认弹窗
      // cancel   关闭弹窗
      if (actions === 'cancel') {
        done()
      } else {
        if (!this.oldPassword) {
          this.$toast.fail('原密码不能为空')
          done(false)
          return
        }
        if (this.oldPassword != this.userInfo.password) {
          this.$toast.fail('原密码不相同')
          done(false)
          return
        }
        if (!this.newPassword) {
          this.$toast.fail('新密码不能为空')
          done(false)
          return
        }
        if (this.newPassword === this.userInfo.password) {
          this.$toast.fail('新密码不能原密码相同')
          done(false)
          return
        }
        user_update(this.userInfo.id, { password: this.newPassword }).then(
          (res) => {
            this.$toast.fail(res.data.message)
            done()
          }
        )
      }
    },
    // 编辑性别
    updateGender(gender) {
      user_update(this.userInfo.id, { gender: gender.gender }).then((res) => {
        this.userInfo.gender = gender.gender
        this.$toast.success(res.data.message)
      })
    },
  },
}
</script>


<style lang="less" scoped>
// /deep/表示样式穿透，用于设置组件内部标签的样式
// （默认情况下，不能设置组件内部标签的样式）
/deep/.van-nav-bar .van-icon {
  color: #000;
}
.van-nav-bar {
  border-bottom: 2px solid #ccc;
}
.content {
  margin: 20px auto;
  .head_img {
    position: relative;
    width: 25%;
    margin: 0 auto;
    img {
      width: 100%;
    }
    /deep/.van-uploader {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      .van-uploader__upload {
        width: 100%;
        height: 100px;
        opacity: 0;
      }
    }
  }
}
.van-cell {
  border-bottom: 1px solid #ccc;
}
</style>